package bb.lanxing.devices.config;

//import com.orm.query.Select;

import java.util.ArrayList;
import java.util.List;

import org.litepal.LitePal;

import bb.lanxing.App;
import bb.lanxing.lib.devices.api.DeviceProvider;
import bb.lanxing.lib.devices.api.SmartDevice;
import bb.lanxing.model.database.Device;
import bb.lanxing.util.Log;

public class AppDeviceProvider implements DeviceProvider {
    @Override
    public SmartDevice create() {
        return new Device();
    }

    @Override
    public List<SmartDevice> getDevicesByType(int i) {
        //return new ArrayList(Device.find(Device.class, "user_id = ? and type = ?", String.valueOf(App.getContext().getUserId()), String.valueOf(i)));
        String userId = String.valueOf(App.getContext().getUserId());

        List<Device> l = LitePal.where("userId = ? and type = ?", userId, String.valueOf(i)).find(Device.class);
        return new ArrayList<>(l);
    }

    @Override
    public SmartDevice getDeviceByAddress(String str) {
        String userId = String.valueOf(App.getContext().getUserId());
        return LitePal.where("address = ?", userId).findFirst(Device.class);
    }

    @Override
    public void save(SmartDevice smartDevice) {
        if (smartDevice instanceof Device) {
            Log.d("AppDeviceProvider", "save flags=" + smartDevice.getFlags()
                    + ", id=" + ((Device) smartDevice).getId() +  ", UserId=" + ((Device) smartDevice).getUserId());
            ((Device) smartDevice).save();
        }
    }

    @Override
    public List<SmartDevice> getDevices() {
//        return new ArrayList(Device.find(Device.class, "user_id = ?", String.valueOf(App.getContext().getUserId())));
        String userId = String.valueOf(App.getContext().getUserId());

        List<Device> l = LitePal.where("userId = ?", userId).find(Device.class);
        return new ArrayList<>(l);

    }

    @Override
    public void removeByType(int i) {
        Device.deleteAll(Device.class, "userId = ? and type = ? ", String.valueOf(App.getContext().getUserId()), String.valueOf(i));
    }

    @Override
    public void removeByTypeAndFlag(int i, int i2) {
//        Device.deleteAll(Device.class, "user_id = ? and type = ? and flags = ? ", String.valueOf(App.getContext().getUserId()), String.valueOf(i), String.valueOf(i2));
        String userId = String.valueOf(App.getContext().getUserId());
        Device.deleteAll(Device.class, "userId = ? and type = ?", userId, String.valueOf(i));
    }

    @Override
    public boolean isSecondGenerationDevice(int i) {
        return Device.isSecondGenerationDevice(i);
    }

    @Override
    public boolean isSensorDevice(int i) {
        return Device.isSensorType(i);
    }

    @Override
    public boolean isAutoConnectDeviceType(int i) {
        return Device.isThisTypeNeedAutoConnect(i);
    }
}
